package com.youi.handler;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.youi.exception.BusinessException;
import com.youi.util.JsonUtil;
import com.youi.util.LogUtil;
/**
 *  全局异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler{

	@ExceptionHandler(value = Exception.class)
	public ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object object, Exception e) {
        try {
            LogUtil.Error(e.getMessage());
            e.printStackTrace();
            if (e instanceof BusinessException) {
        		BusinessException be=(BusinessException) e;
        		response.setCharacterEncoding("utf-8");
        		response.setContentType("application/json; charset=utf-8");
    	        response.getWriter().print(JsonUtil.toJson(be.getErrorcode(),be.getMessage()));
			}else  if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
                //404 Not Found
            	response.getWriter().print(JsonUtil.toJson(404,e.getMessage()));
            } else {
                //500
            	response.getWriter().print(JsonUtil.toJson(500,e.getMessage()));
            }
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}
	
}

